/* eslint-disable @typescript-eslint/no-inferrable-types */
import {
  Controller,
  Post,
  Body,
  Req,
  UseGuards,
  Delete,
  Param,
  Patch,
  Get,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  Query,
} from '@nestjs/common';
import { OrdersService } from './orders.service';
import { CreateOrderDto } from 'src/dto/create-order.dto';
import { Request } from 'express';
import { JwtAuthGuard } from 'src/guards/jwt-auth.guard';
import { FindDataDto } from 'src/dto/find-data.dto';
import { OrderDto, OrderState } from 'src/dto/order.dto';
import { JwtPayload } from '../tokens/jwt.payload';

@UseGuards(JwtAuthGuard)
@Controller('orders')
export class OrdersController {
  constructor(private readonly ordersService: OrdersService) {}

  /**
   * 创建一个订单
   * @param req 请求体
   * @param createOrderDto 创建的订单部分信息
   */
  @Post()
  async createOrder(
    @Req() req: Request,
    @Body() createOrderDto: CreateOrderDto,
  ) {
    const user = req.user as JwtPayload;
    await this.ordersService.create(user._id, createOrderDto);
  }

  /**
   * 删除一个订单
   * @param _id _id
   */
  @Delete(':_id')
  async deleteOrder(@Param('_id') _id: string) {
    await this.ordersService.deleteById(_id);
  }

  /**
   * 更新一个订单状态
   * @param _id _id
   * @param state 订单状态
   */
  @Patch(':_id/state')
  async updateOrderState(
    @Param('_id') _id: string,
    @Body('state') state: OrderState,
  ) {
    await this.ordersService.updateState(_id, state);
  }

  /**
   * 查询一些订单
   * @param pageIndex 页码
   * @param pageSize 页大小
   */
  @Get()
  async findOrders(
    @Query('pageIndex') pageIndex: number = 1,
    @Query('pageSize') pageSize: number = 10,
    @Query('keyword') keyword: string = '',
  ) {
    const data = await this.ordersService.find({
      pageIndex,
      pageSize,
      keyword,
    });
    const total = await this.ordersService.count({ keyword });

    return {
      total,
      pageIndex,
      pageSize,
      keyword,
      data,
    } as FindDataDto<OrderDto>;
  }
}
